from abc import ABC
import os
import json

from Server.Handlers.basic import FileServerRequestHandler, Param
from Server.Utils import fileType
from Server import const


class UploadHandle(FileServerRequestHandler, ABC):
    def post(self):
        if not Param.EnableFileUpload:
            self.set_status(403)
            self.writeFormat(False, '管理员关闭了文件上传功能，无法上传！！！')
            return
        try:
            body = json.loads(self.request.body)
            data = bytes(body['bytes'], encoding='iso-8859-1')
            uploadingFileName = body['filename'] + const.UploadingFileExtension
            routeFrom = body['rf']
            path = Param.RoutePath[routeFrom] + body['path'][len(routeFrom):]
            if path[-1] != '/':
                path += '/'
            if body['seq'] == 1:
                with open(path + uploadingFileName, 'wb') as f:
                    f.write(data)
                    f.close()
            else:
                with open(path + uploadingFileName, 'ab') as f:
                    f.write(data)
                    f.close()
            if body['seq'] == body['total']:
                fileType.deleteFile(path + body['filename'])
                os.rename(path + uploadingFileName, path + body['filename'])
            self.set_status(200)
        except PermissionError:
            self.set_status(403)
            self.writeFormat(False, '当前目录无法创建新文件！！！')
        except OSError:
            self.set_status(400)
            self.writeFormat(False, '未知系统错误，已记入后台日志')
        except:
            self.set_status(400)
            self.writeFormat(False, '请求参数错误')
